package com.lanou.dllo.findfood.activity;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.bartoszlipinski.recyclerviewheader.RecyclerViewHeader;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lanou.dllo.findfood.R;
import com.lanou.dllo.findfood.adpter.HotSeachAdpter;
import com.lanou.dllo.findfood.dialog.CookProgressDialog;
import com.lanou.dllo.findfood.entity.FindMenu;
import com.lanou.dllo.findfood.tools.StringUtil;
import com.lanou.dllo.findfood.tools.ToastCommon;
import com.lanou.dllo.findfood.util.HotSeacherClick;
import com.lanou.dllo.findfood.volley.VolleySington;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by dllo on 15/10/26.
 */
public class HotMenuActivity extends Activity implements View.OnClickListener, HotSeacherClick {
    private ImageView back;
    private TextView searchName, sumMenu;
    private RecyclerView recyclerView;
    private AutoCompleteTextView nameStr;
    private String name;
    private Button search_btn, clear;//设置搜索和清空的按钮
    private RecyclerViewHeader viewHeader;
    private HotSeachAdpter adpter;
    private ArrayAdapter<String> arr_adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_hotmenu);
        initView();
        autoText();

    }

    public void autoText() {
        //定义一个缓存文件
        SharedPreferences sp = getSharedPreferences("search_history", 0);
        String history = sp.getString("history", "暂时没有搜索记录");

        // 用逗号分割内容返回数组
        String[] history_arr = history.split(",");

        // 新建适配器，适配器数据为搜索历史文件内容
        arr_adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_dropdown_item_1line, history_arr);

        // 保留前50条数据
        if (history_arr.length > 50) {
            String[] newArrays = new String[50];
            // 实现数组之间的复制
            System.arraycopy(history_arr, 0, newArrays, 0, 50);
            arr_adapter = new ArrayAdapter<String>(this,
                    android.R.layout.simple_dropdown_item_1line, history_arr);
        }

        // 设置适配器
        nameStr.setAdapter(arr_adapter);
    }

    public void save() {
        // 获取搜索框信息
        String text = nameStr.getText().toString();
        SharedPreferences mysp = getSharedPreferences("search_history", 0);
        String old_text = mysp.getString("history", "暂时没有搜索记录");

        // 利用StringBuilder.append新增内容，逗号便于读取内容时用逗号拆分开
        StringBuilder builder = new StringBuilder(old_text);
        builder.append(text + ",");

        // 判断搜索内容是否已经存在于历史文件，已存在则不重复添加
        if (!old_text.contains(text + ",")) {
            SharedPreferences.Editor myeditor = mysp.edit();
            myeditor.putString("history", builder.toString());
            myeditor.commit();
            Toast.makeText(this, text + "添加成功", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, text + "已存在", Toast.LENGTH_SHORT).show();
        }
    }

    //清除搜索记录
    public void cleanHistory(View v) {
        SharedPreferences sp = getSharedPreferences("search_history", 0);
        SharedPreferences.Editor editor = sp.edit();
        editor.clear();
        editor.commit();
        Toast.makeText(this, "清除成功", Toast.LENGTH_SHORT).show();
        super.onDestroy();
    }

    public void initView() {
        back = (ImageView) findViewById(R.id.back);
        back.setOnClickListener(this);
        searchName = (TextView) findViewById(R.id.searchName);
        sumMenu = (TextView) findViewById(R.id.sumMenu);
        nameStr = (AutoCompleteTextView) findViewById(R.id.nameStr);
        recyclerView = (RecyclerView) findViewById(R.id.searchRecylerView);
        GridLayoutManager layoutManager = new GridLayoutManager(this, 2);
        adpter = new HotSeachAdpter();
        recyclerView.setAdapter(adpter);
        recyclerView.setLayoutManager(layoutManager);
        viewHeader = (RecyclerViewHeader) findViewById(R.id.hotHeader);
        viewHeader.attachTo(recyclerView, true);
        adpter.setImage(this);
        search_btn = (Button) findViewById(R.id.search_btn);
        search_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                initData();
                save();
            }
        });

    }

    String path;

    private void initData() {

        name = nameStr.getText().toString();//将输入的菜名显示出来
        searchName.setText(name);
        if (name.length() == 0) {
            ToastCommon.createToastConfig().ToastShow(this, (ViewGroup) findViewById(R.id.toast_layout_root),
                    "输入菜名(^__^),用为您查询出准确的菜谱哦!");
        }

        String httpUrl = "http://apis.baidu.com/tngou/cook/name";
        String httpArg = "name=" + StringUtil.utf8Encode(name);
        path = httpUrl + "?" + httpArg;


        final CookProgressDialog anmition = new CookProgressDialog(this, R.id.animaImg);
        anmition.show();
        StringRequest request = new StringRequest(path, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Gson gson = new Gson();
                List<FindMenu> menuList = gson.fromJson(response
                        , new TypeToken<List<FindMenu>>() {
                }.getType());
                //  searchName.setText(name);
                sumMenu.setText(menuList.size() + "");
                adpter.addData(menuList);
                anmition.dismiss();
            }


        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
            }
        }) {
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                map.put("apikey", "7df89e2ed7c7b92e1a2fe5ec8036d0cd");
                return map;
            }
        };
        VolleySington.getInstance().addRequest(request);


    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back:
                finish();

                break;

            default:
                break;

        }

    }

    @Override
    public void HotSeacherClick(FindMenu result) {
        Intent intent = new Intent(this, MenuDescipetinActivity.class);
        intent.putExtra("id", result.getId());
        startActivityForResult(intent, 100);
    }
}
